package com.igeek.ssm.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * @Description TODO
 * @Author chenmin
 * @Version 1.0
 * @Date 2023/1/12 14:59
 *
 * web初始化 ：取代web.xml的启动配置
 * 一旦Tomcat容器启动，加载WebInitializer中onStartup()
 */
public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //创建IOC容器
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        //在IOC容器中，注册配置类
        ac.register(SpringMVCConfig.class , MyBatisConfig.class);

        //创建编码集过滤器  放置POST请求乱码
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", new CharacterEncodingFilter("UTF-8"));
        //设置过滤路径
        encodingFilter.addMappingForUrlPatterns(null , true , "/*");
        //在IOC容器中，设置过滤器
        ac.setServletContext(servletContext);

        //创建前端控制器
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(ac));
        //设置前端控制器处理的请求  RESTFul风格 HTTP动词 POST、GET、PUT、DELETE
        dispatcher.addMapping("/");
        //Tomcat一启动，实例化前端控制器
        dispatcher.setLoadOnStartup(1);
    }
}
